package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("请提供一个 .ts 文件作为参数")
		return
	}
	filePath := os.Args[1]
	data, err := readFile(filePath)
	if err != nil {
		fmt.Printf("读取文件时出错: %v\n", err)
		return
	}
	replacedData := performReplacements(data)
	err = writeFile(filePath, replacedData)
	if err != nil {
		fmt.Printf("写入文件时出错: %v\n", err)
		return
	}
	fmt.Println("替换完成")
}

func readFile(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
	return strings.Join(lines, "\n"), nil
}

func performReplacements(data string) string {
	replacements := []struct {
		old string
		new string
	}{
		{"(`/api/v1/", "({url:`/api/v1/"},
		{", req)", ", params: req})"},
		{", params)", ", params})"},
		{"${id}`, params: req", "${req.id}`, params: req"},
		{"${id}`, params", "${params.id}`, params"},
		{".CommonIdReqParams, id: number) {", ".CommonIdReqParams) {"},
		{"({url:`/api/v1/", "({url:`/"},
	}
	for _, r := range replacements {
		data = strings.ReplaceAll(data, r.old, r.new)
	}
	return data
}

func writeFile(filePath string, data string) error {
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	_, err = writer.WriteString(data)
	if err != nil {
		return err
	}
	return writer.Flush()
}
